﻿using UnityEditor;
using UnityEngine;

namespace XFramework
{

    public class BatchGenerateChild : EditorWindow
    {
        private GameObject _child;
        private bool _isSame = false;
        private bool _isReserveTransform = false;

        private void OnGUI()
        {
            GUILayout.BeginVertical();
            GUILayout.Space(10);
            GUI.skin.label.fontSize = 24;
            GUI.skin.label.alignment = TextAnchor.MiddleCenter;
            GUILayout.Label("批量添加子物体");
            GUILayout.Space(10);
            _child = (GameObject)EditorGUILayout.ObjectField("请拖入预制体", _child, typeof(GameObject));
            GUILayout.Space(10);
            _isSame = GUILayout.Toggle(_isSame, "生成子物体名称是否与预制体名称一致?");
            GUILayout.Space(10);
            _isReserveTransform = GUILayout.Toggle(_isReserveTransform, "是否保留预制体Transform信息？不勾为重置状态");
            GUILayout.Space(60);
            GUI.skin.label.fontSize = 16;
            GUI.skin.label.alignment = TextAnchor.MiddleCenter;
            GUILayout.Label("选中物体后点击生成即可！");
            GUILayout.Space(10);
            if (GUILayout.Button("生成"))
            {
                InstantiateChild();
            }

            GUILayout.EndVertical();
        }

        private void InstantiateChild()
        {
            var objs = Selection.gameObjects;
            foreach (var go in objs)
            {
                var insgo = GameObject.Instantiate(_child.transform, Vector3.zero, Quaternion.identity, go.transform);
                if (_isSame) insgo.name = _child.name;

                if (_isReserveTransform == false)
                {
                    insgo.transform.localPosition = Vector3.zero;
                    insgo.transform.rotation = Quaternion.identity;
                    insgo.transform.localScale = Vector3.zero;
                }

            }
        }
    }
}